<template>
  <FPage v-loading="loading">
    <template #header>
      <CommonCountListWrapper v-show="showCount">
        <CommonCountComponent @click="openDepartManagerModal" :count="unitCount.departCount" desc="部门"/>
        <CommonCountComponent @click="openPositionManagerModal" :count="unitCount.positionCount" desc="岗位"/>
        <CommonCountComponent @click="openPositionLevelManagerModal"
                              :count="unitCount.positionLevelCount" desc="职务级别"/>
        <CommonCountComponent @click="openUserManageModal" :count="unitCount.userCount"
                              desc="人员"/>
        <CommonCountComponent @click="openRoleManagerModal" :count="unitCount.roleCount" desc="单位角色"/>
        <CommonCountComponent @click="openGroupManagerModal" :count="unitCount.groupCount" desc="组"/>
        <CommonCountComponent desc="人员排序"/>
      </CommonCountListWrapper>
    </template>

    <div class="unit-editor-body">
      <div class="unit-editor-left">
        <el-text style="margin-left: 10px; margin-top: 10px" tag="b" truncated>
          单位基本信息
        </el-text>
        <el-form ref="refLeftForm" label-width="150px" :model="unitData">
          <el-form-item prop="unitName" label="单位名称" :rules="[required]">
            <el-input placeholder="请输入单位名称" v-model="unitData.unitName"/>
          </el-form-item>

          <el-form-item prop="simpleName" label="单位简称" :rules="[required]">
            <el-input placeholder="请输入单位简称" v-model="unitData.simpleName"/>
          </el-form-item>

          <el-form-item prop="unitCode" label="单位编码" :rules="[required]">
            <el-input placeholder="请输入单位编码" v-model="unitData.unitCode"/>
          </el-form-item>

          <el-form-item prop="sort" label="排序号" :rules="[required]">
            <el-input-number style="width: 100%" placeholder="请输入排序号"
                             v-model="unitData.sort"/>
          </el-form-item>

          <el-form-item prop="unitStatus" label="单位状态" :rules="[required]">
            <SystemDict dict-code="unitStatus" v-model="unitData.unitStatus" placeholder="请选择单位状态"/>
          </el-form-item>

          <el-form-item prop="unitDesc" label="单位描述" :rules="[]">
            <el-input type="textarea" v-model="unitData.unitDesc" placeholder="请输入单位描述"/>
          </el-form-item>

          <el-form-item prop="parentId" label="上级单位" :rules="[required]">
            <el-tree-select style="width: 100%" :props="defaultProps"
                            v-model="unitData.parentId"
                            :data="unitTreeData" default-expand-all
                            check-strictly node-key="id"
                            :render-after-expand="false"
            />
          </el-form-item>
          <el-form-item v-if="isNewUnit" prop="copyPosition" label="复制集团基准岗" :rules="[]">
            <el-checkbox v-model="unitData.copyPosition" true-label="1" false-label="0"/>
          </el-form-item>

          <el-form-item v-if="isNewUnit" prop="copyPositionLevel" label="复制集团职务级别" :rules="[]">
            <el-checkbox v-model="unitData.copyPositionLevel" true-label="1" false-label="0"/>
          </el-form-item>
        </el-form>
      </div>

      <div class="unit-editor-right">
        <el-form ref="refRightForm" label-width="120px" :model="unitData">
          <template v-if="isNotEmpty(unitData.unitRoles)">
            <el-text style="margin-left: 10px; margin-top: 10px" tag="b" truncated>
              单位角色信息
            </el-text>
            <el-form-item v-for="unitRole in unitData.unitRoles"
                          :label="unitRole.roleName">
              <MultiUserSelector v-model:usersId="unitRole.userIds"
                                 :tabsConfig="userSelectTabsConfig"
                                 v-model:usersName="unitRole.userNames"/>
            </el-form-item>
          </template>
          <!--          <el-form-item prop="unitType" label="单位管理员">-->
          <!--            <MultiUserSelector v-model:usersId="unitData.unitAdministratorId"-->
          <!--                               :tabsConfig="userSelectTabsConfig" :disabled="isNewUnit"-->
          <!--                               v-model:usersName="unitData.unitAdministratorName"/>-->
          <!--          </el-form-item>-->
          <el-text style="margin-left: 10px; margin-top: 10px" tag="b" truncated>
            单位说明信息
          </el-text>

          <el-form-item prop="unitType" label="单位类型">
            <SystemDict dict-code="unitType" placeholder="请选择单位类型"
                        v-model="unitData.unitType"/>
          </el-form-item>

          <el-form-item prop="unitLegalPerson" label="负责人(法人)" :rules="[]">
            <el-input placeholder="请输入负责人(法人)" v-model="unitData.unitLegalPerson"/>
          </el-form-item>

          <el-form-item prop="pos" label="地址" :rules="[]">
            <el-input placeholder="请输入地址" v-model="unitData.pos"/>
          </el-form-item>

          <el-form-item prop="postal" label="邮编" :rules="[]">
            <el-input placeholder="请输入邮编" v-model="unitData.postal"/>
          </el-form-item>

          <el-form-item prop="tel" label="电话" :rules="[]">
            <el-input placeholder="请输入电话" v-model="unitData.tel"/>
          </el-form-item>

          <el-form-item prop="fax" label="传真" :rules="[]">
            <el-input placeholder="请输入传真" v-model="unitData.fax"/>
          </el-form-item>

          <el-form-item prop="website" label="网址" :rules="[]">
            <el-input placeholder="请输入网址" v-model="unitData.website"/>
          </el-form-item>

          <el-form-item prop="email" label="邮编地址" :rules="[]">
            <el-input placeholder="请输入邮编地址" v-model="unitData.email"/>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <template #footer>
      <div class="group-desc-footer">
        <el-button round icon="cancel" @click="cancel">取消</el-button>
        <el-button round icon="ok" type="primary" @click="ok">确定</el-button>
      </div>
    </template>
    <DepartManagerModal ref="refDepartManagerModal"/>
    <PositionManagerModal ref="refPositionManagerModal"/>
    <PositionLevelManagerModal ref="refPositionLevelManagerModal"/>
    <UserManageModal ref="refUserManageModal"/>
    <RoleManagerModal ref="refRoleManagerModal"/>
    <GroupManagerModal ref="refGroupManagerModal"/>
  </FPage>
</template>
<script setup>
import CommonCountListWrapper from '@/views/system/UnitManagement/CommonCountListWrapper/index.vue';
import CommonCountComponent from '@/views/system/UnitManagement/CommonCountComponent/index.vue';
import {computed, ref, shallowRef, toRaw, unref, watch} from 'vue';
import FPage from '@/components/layout/FPage.vue';
import {isEmpty, isNotEmpty, required, treesToList} from '@/utils/CommonUtils';
import SystemDict from '@/components/SystemDict';
import MultiUserSelector from '@/components/MultiUserSelector/index.vue';
import {loadUnits} from '@/request';
import {getAction, postAction} from '@/request/BaseRequest';
import DepartManagerModal from '@/views/system/UnitManagement/DepartManagerModal/index.vue';
import PositionManagerModal from '@/views/system/UnitManagement/PositionManagerModal/index.vue';
import PositionLevelManagerModal from '@/views/system/UnitManagement/PositionLevelManagerModal/index.vue';
import UserManageModal from '@/views/system/UnitManagement/UserManageModal';
import RoleManagerModal from '@/views/system/UnitManagement/RoleManagerModal/index.vue';
import GroupManagerModal from '@/views/system/UnitManagement/GroupManagerModal/index.vue';

defineOptions({
  name: 'UnitEditComponent',
});

const emits = defineEmits(['reloadUnits', 'selectChange']);
const loading = shallowRef(false);
const refRightForm = shallowRef();
const refDepartManagerModal = shallowRef();
const refLeftForm = shallowRef();
const refPositionManagerModal = shallowRef();
const refPositionLevelManagerModal = shallowRef();
const refUserManageModal = shallowRef();
const refRoleManagerModal = shallowRef();
const refGroupManagerModal = shallowRef();
const userSelectTabsConfig = shallowRef([
  {name: 'depart'},
  {name: 'position'},
  {name: 'positionLevel'}
]);
const defaultProps = {
  children: 'children',
  label: 'unitName',
};
const unitData = ref({
  unitRoles: [
    // {
    //   id: '',
    //   roleName: 'asdf',
    //   userIds: '',
    //   userNames: ''
    // }
  ]
});
const unitTreeData = shallowRef([]);
const props = defineProps({
  unit: undefined
});
const unitCount = shallowRef({});

function loadUnitCounts() {
  if (isAddNew()) {
    setDefaultUnitData();
  } else {
    loading.value = true;
    getAction('/sys/unit/loadUnitCountById',
      {id: props.unit.id}).then(data => {
      loading.value = false;
      if (data.success) {
        unitCount.value = data.result;
      }
    });
  }
}

function loadUnit() {
  if (isAddNew()) {
    setDefaultUnitData();
  } else {
    loading.value = true;
    getAction('/sys/unit/loadUnitById',
      {id: props.unit.id}).then(data => {
      loading.value = false;
      if (data.success) {
        let result = data.result;
        setUnitData(result);
      }
    });
  }
}

function openGroupManagerModal() {
  refGroupManagerModal.value.setData(unitData);
}

function openRoleManagerModal() {
  refRoleManagerModal.value.setData(unitData);
}

function openUserManageModal() {
  refUserManageModal.value.setData(unitData);
}

function openPositionLevelManagerModal() {
  refPositionLevelManagerModal.value.setData(unitData);
}

function openPositionManagerModal() {
  refPositionManagerModal.value.setData(unitData);
}

function openDepartManagerModal() {
  refDepartManagerModal.value.setData(unitData);
}

function setUnitData(result) {
  unitData.value = result;
}

function setDefaultUnitData() {
  unitData.value.unitStatus = '0';
  unitData.value.copyPosition = '1';
  unitData.value.copyPositionLevel = '1';
  unitData.value.unitGroup = false;
  unitData.value.parentId = undefined;
  unitData.value.type = 0;
  try {
    unitData.value.parentId = unitTreeData.value[0].id;
  } catch (e) {
  }
  loadMaxUnitSort();
}

function loadMaxUnitSort() {
  loading.value = true;
  getAction('/sys/unit/loadMaxUnitSort').then(data => {
    loading.value = false;
    if (data.success) {
      let result = data.result;
      unitData.value.sort = result;
    }
  });
}

function isAddNew() {
  if (isEmpty(props.unit) || isEmpty(props.unit.id)) {
    return true;
  }
  return false;
}

function cancel() {
  emits('selectChange', undefined);
  unitData.value = unitData;
}

function ok() {
  refLeftForm.value.validate((valid, errors) => {
    if (valid) {
      let data = getUnitData();
      doSave(data);
    }
  });
}

function getUnitData() {
  return unref(unitData);
}

function doSave(data) {
  data = unref(data);
  data = toRaw(data);

  let method = undefined;
  if (isNotEmpty(data.id)) {
    method = postAction('/sys/unit/saveUnit', data);
  } else {
    method = postAction('/sys/unit/saveUnit', data);
  }

  loading.value = true;
  method.then(data => {
    loading.value = false;
    if (data.success) {
      unitData.value = data.result;
      emits('reloadUnits', () => {
        emits('selectChange', data.result);
      });
    }
  });
}

function loadUnitTree() {
  return new Promise((success, err) => {
    loading.value = true;
    loadUnits().then(trees => {
      loading.value = false;
      unitTreeData.value = trees;
      try {
        treesToList(trees).forEach(node => {
          if (node.id === props.unit.id) {
            node.disabled = true;
          }
        });
      } catch (e) {
      }
      success();
    });
  });
}

const isNewUnit = computed(() => {
  return isEmpty(props.unit) || isEmpty(props.unit.id);
});

function loadPageData() {
  loadUnitTree().then(() => {
    loadUnit();
    loadUnitCounts();
  });
}

const showCount = computed(() => {
  return isNotEmpty(unitData.value.id);
});

watch(() => [props.unit], () => {
  loadPageData();
}, {immediate: true});
</script>
<style>
.unit-editor-body {
  width: 100%;
  display: flex;
  height: 100%;
  background: white;
  overflow: auto;
  border: 2px solid #f0f2f5;
  box-sizing: border-box;
}

.unit-editor-left {
  flex: 0.5;
  padding-right: 30px;
}

.unit-editor-right {
  flex: 0.5;
  padding-right: 30px;
}

.group-desc-footer {
  text-align: right;
  padding: 5px 10px;
}
</style>
